package com.design.graduation.asdemo.network.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.design.graduation.asdemo.network.model.ErrorResult;
import com.design.graduation.asdemo.utils.ToastUtil;
import com.uzteam.common.log.Logger;
import com.uzteam.common.utils.JSONUtils;

import java.io.IOException;
import java.net.SocketTimeoutException;

import retrofit.HttpException;

import rx.Observer;

/**
 * Created by liyugang on 10/26/15.
 */
public abstract class HttpObserver<T> implements Observer<T> {
    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {

        if (e instanceof SocketTimeoutException) {
            ToastUtil.showShortToast("请求超时，稍后再试");
            return;
        }
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            retrofit.Response<T> response = (retrofit.Response<T>) httpException.response();
            try {
                onFailure(response.code(), response.errorBody().string());
            } catch (JSONException jsonException) {
                jsonException.printStackTrace();
                ToastUtil.showShortToast("服务器开小差了，稍后再试...");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            } catch (Exception exception) {
                exception.printStackTrace();
                throw exception;
            }
        }
    }

    @Override
    public void onNext(T t) {
        Logger.json(JSONUtils.toJSONString(t));
        onSuccess(t);
    }

    public abstract void onSuccess(T t);

    public abstract void onNetworkError();

    public void onFailure(int responseCode, String json) {
        Logger.e(json);
        ErrorResult errorResult = JSON.parseObject(json, ErrorResult.class);
        ToastUtil.showShortToast(errorResult.getMessage());
    }
}
